<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from "vue";
import { storeToRefs } from "pinia";
import { useTradeStore } from "@/store/modules/tradeStore";
import Position from "@/components/tables/account/Position.vue";
import type { PositionSchema } from "@/types/account.types";

defineOptions({
  name: "trade-position-table"
});

const props = withDefaults(
  defineProps<{
    title?: string;
    compact?: boolean;
    height?: string | null;
  }>(),
  {
    title: undefined,
    compact: false,
    height: null
  }
);

const tradeStore = useTradeStore();
const { accountInfo } = storeToRefs(tradeStore);

const positions = computed(() =>
  accountInfo.value ? Array.from(accountInfo.value.positions.values()) : []
);

// writable selected position id
const selectedPositionId = computed({
  get: () => tradeStore.selectedPositionId,
  set: (value: string | null) => {
    tradeStore.setSelectedPositionId(value);
  }
});

const tableContainerRef = ref<HTMLElement | null>(null);
const tableHeight = ref<string | null>();

// Use provided height or calculate it
const effectiveHeight = computed(() => props.height || tableHeight.value);

const updateTableHeight = () => {
  if (!props.height && tableContainerRef.value) {
    tableHeight.value = `${tableContainerRef.value.clientHeight}px`;
  }
};

onMounted(() => {
  if (!props.height) {
    updateTableHeight();
    window.addEventListener("resize", updateTableHeight);
  }
});

onUnmounted(() => {
  if (!props.height) {
    window.removeEventListener("resize", updateTableHeight);
  }
});
</script>

<template>
  <div ref="tableContainerRef" class="h-full w-full overflow-hidden">
    <Position
      v-model:selected-position-id="selectedPositionId"
      :positions="positions"
      :height="effectiveHeight"
      :title="props.title"
      :compact="props.compact"
      size="small"
    />
  </div>
</template>
